package com.itheima.web.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

// 读取Cookie数据
@WebServlet("/bServlet")
public class BServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.调用request.getCookies()返回一个Cookie对象数组
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            // 2.如果不为空，则遍历每个Cookie对象
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if (name.equals("username")) {
                    // 存储的是中文,需要解码
                    value = URLDecoder.decode(value, "UTF-8");
                }

                System.out.println(name + " : " + value);
            }
         } else {
            // 3.如果数组为null，打印没有读取到Cookie
            System.out.println("没有Cookie");
        }
    }
}
